define(['apps/utils/tools','apps/utils/chart','apps/kemu'],function (tools,chart,kemu){
  var domId = "content",tableId = "tableId",componentExp = "#indicatorDiv>dl>dd>a",dimArr=[],dimCode="indicator";
  var flag = false;//此变量用来识别事件是否第一次绑定了啊
  var manyDim = {},queryParams = {},defaultChartSwf = "Column3D";
  var showColDim = ["inputIndicator","inputCompany","inputPeriod"];//表格列显示显示隐藏的变量
  function setSelect(obj){
       if(!$(obj).hasClass(tools.cls)){
		        $(obj).addClass(tools.cls)
	  }
  }
  function removeSelect(obj){
     if($(obj).hasClass(tools.cls)){
		   $(obj).removeClass(tools.cls).addClass("btn-default");
	 }
  }
   function allSelectEvent(){
          $(componentExp).each(function(index,obj){setSelect(obj);});
  }
   function clearSelectEvent(){
        $(componentExp).each(function(index,obj){
          	   removeSelect(obj)
        });
  }
  function allSelect(){
     $("#allSelect").click(function(){
          $(componentExp).each(function(index,obj){setSelect(obj);});
     });
  }
  function clearSelect(){
     $("#clearSelect").click(function(){
          clearSelectEvent();
     });
  }
  function createDim(dimArr){
     var datas ='',selectData='',sname="";// '<dl class="dl-horizontal"> <dt>指标</dt><dd class="box" name="indicator">';
        for (var i = 0; i < dimArr.length; i++){
        	var n = dimArr[i]["name"],c=dimArr[i]["scode"],cls = "btn btn-primary ";
        	if(i != 0){
        		cls+=dimCode;
        	}
        	 datas+='<a title="'+n+'" href="javascript:;" class="'+cls+'" scode="'+c+'">'+n+'</a>';
             selectData+='<option value="'+c+'">'+n+'</option>';
             if(i<8){
                sname+=n+"&nbsp;";
             }
        }
         tools.levelNav({scode:dimArr[0]["scode"],sname:"所选指标【"+sname+"】",level:3});
	     tools.navEventBind();
	    $("dd[name="+dimCode+"]").empty().append(datas);
     	$("#"+dimCode).empty().append(selectData).attr('multiple','multiple');//multiple="multiple"
     	$("#"+dimCode+" option").attr("selected","selected");
         return datas;
  }
  /**
   * 给选择后的指标indicator维度下的组件 绑定事件
   * 根据传过来选中的指标多少是确定是否多选还是单选
   */
  function bindIndicatorDimTwo(arr){
  	  var len = arr.length;
  	  if(len>1){
  	    // tools.alertMsg("多选的指标！");
  	  }
  	  if(len == 1){
  	     //tools.alertMsg("单选的指标！");
  	  }
  	  componentEventAbind(dimCode,dimArr);
      componentEventSelectbind(dimCode,dimArr);	
  }
  /**
   * 获取选中的指标
   */
  function getSelectIndicator(){
   
  	var arr = [],result={};
  	 $(componentExp).each(function(index,obj){
      	   if($(obj).hasClass(tools.cls)){
	         arr.push({scode:$(obj).attr("scode"),name:$(obj).text()});
	        }
     });
     var len = arr.length;
     if(len == 0){
       result =  {flag:false,msg:"您没有选中一个！至少选中一个"};
     }else{
          result =  {flag:true,msg:createDim(arr)};
          tools.console(arr);
     }
     bindIndicatorDimTwo(arr);
     return result;
  }
  function sureClickEvent(){
     	var bean = getSelectIndicator();
     	if(!bean.flag){
     		 tools.alertMsg(bean.msg);
     	  return;
     	}
        tools.otherDimShow();
        if(flag == true){
        }
        flag = true;
     
  }
   /**
     * 确定按钮事件
     */
  function sureClick(){
     $("#sure").click(function(){
     sureClickEvent();
     });
  }
  /**
   * 手动绑定字母导航事件
   */
  function letterEventBind(){
        $("li[scroll=1]").click(function(){
			 var id = $(this).attr("scode");//,height = $('#'+id).offset().top-83;
			 $('body,html').animate({scrollTop:$('#'+id).offset().top-83},600);return false;
		});
  }
  /**
   * 操作按钮事件
   */
  function btnGroupBind(){
     $("#groupIds>a").click(function(){//target
			var id=$(this).attr("id"),target = $(this).attr("target"),hiddenDomId = $(this).attr("hiddenDomId");
		    if(id != "dataBoth"){
		       // $(target).fadeIn("slow").siblings().fadeOut("fast");
		    	$(target).fadeIn("slow");
		    	$(hiddenDomId).fadeOut("fast")
		    }else{
		      $(target).fadeIn("slow");
		    }
			
		    tools.styleChange(this);
		    //$(this).addClass(tools.cls).siblings().removeClass(tools.cls).addClass("btn-default");
		});
  }
   /**
   * 排除indicator维度下的组件 绑定事件
   */
  function bindExpInDim(dimArr){
		for(var i=0,len=dimArr.length;i<len-1;i++){
			if(dimArr[i] != "company"){
		     var css = "applyCls";
		      $("dd[name="+dimArr[i]+"]>a").addClass("applyCls");
			}
		   $("#"+dimArr[i]).attr('multiple','multiple');//multiple="multiple"
		}
  }
    /**
     * select 事件绑定
     */
	function dimSelectEventBind(dimArr){
    	for(var i=0,len=dimArr.length;i<len-1;i++){
    	    componentEventSelectbind(dimArr[i],dimArr);
    	}
    }
//    function getDimInfo(dim){
//      var dimLen = 0,value=[];
//      $("dd[name="+dim+"] >a").each(function(index,o){
//	     if($(o).hasClass(tools.cls)){
//	       dimLen++;
//	       value.push({scode:$(o).attr("scode"),name:$(o).text()});
//	     }
//      });
//      var dimName = $("dd[name="+dim+"] >a").parent().prev().text();
//      return {dim:dim,size:dimLen,dimName:dimName,value:value};
//    }
    /**
     * 当a选择时
     */
    function styleChangeA(obj){
    	var dim = obj["dim"],msgBean = {},singleSelect = {dimName:'指标',dim:'indicator',msg:'',flag:true};//regCls = "btn btn-primary applyCls";
    	for(var i=0,len=dimArr.length;i<len;i++){
    		 var aDim = dimArr[i],sel={};
    		  var bb = tools.getDimInfo(aDim),
    		  dimLen = bb.size;var dimName =bb["dimName"];
    		var msg = '',flag=true;
    		 if(dimLen>1){
    		    msg = "维度【"+dimName+"】已经多选了！";
    		    singleSelect["msg"]= msg;
    		    if(aDim == "month" || aDim == "year"){
    		       dimName="期间";
    		    }
    		    singleSelect["dimName"]= dimName;
    		    singleSelect["dim"]= aDim;
    		    singleSelect["flag"]= false;
    		    singleSelect["size"]= dimLen;
    		 }
    		 msgBean[aDim] = {sel:sel,dim:aDim,flag:flag,msg:msg,size:dimLen};
    	}
    	if(singleSelect.msg != ''){
    	  tools.console("点击之前=="+dim+">>>多选的是=="+singleSelect.msg+singleSelect.dim);
    	}else{
    	}
    	
    	if(null != obj["dom"]){//A过来的
	    	var $o = $(obj["dom"]);
	    	if(!singleSelect["flag"]){//如果不是单选：即多选
	    		 if(singleSelect["dim"] == dim){//如果多选的维度等于点击的维度
	    		   if(singleSelect["size"]>1){//即：至少保留一个是选中的
	    		       if(!$o.hasClass(tools.cls)){
	    		           $o.addClass(tools.cls);
	    		           return {flag:"add"};
	    		       }else{
	    		           removeSelect(obj["dom"]);
	    		           return {flag:"remove"};
	    		       }
	    		   }
	    		}else{//remove:msgBean[dim]["sel"]
	    			tools.styleChange(obj["dom"]);
	    			return {dim:dim,flag:"single"};
	    		}
	    	}else{////如果单选
	    	   setSelect(obj["dom"]);
	    	   return {flag:"add"};
	    	}
    	}else{//select过来的
    	      var valArr = $("#"+dim).val(),len = valArr.length;
    	      if(!singleSelect["flag"] && len>1){//如果不是单选：即多选
    	      	    tools.alertMsg("select过来的两个多选的 !有时候再加吧！");
    	      }else{
    	           for(var y=0;y<len;y++){
    	             $("dd[name="+dim+"] >a").each(function(index,o){
    	             	if($(o).attr("scode") == valArr[y]){
    	             	     setSelect(o);
    	             	}else{
    	             	    removeSelect(o);
    	             	}
    		         });
    	      }
    	      }
    	      
    	   
    	}
    	/*if($(obj["dom"]).hasClass(tools.cls)){
    	   alert($(obj["dom"]).text()+"已经选中了");
    	}else{
    	   alert($(obj["dom"]).text()+"没有选中了");
    	}*/
    	
    }
    /**
     * 当select选择时
     */
    function styleChangeSelect(obj){
    
    }
     function componentEventSelectbind(dim,dimArr){
    	  $("#"+dim).unbind();  
    	  tools.console("给Select--"+dim+"绑定了事件--->");
    	  $("#"+dim).bind("change",function(){
    	  	  dim = $(this).attr("id");
    	  	  var val = $(this).val();
    	  	 /* for(var x=0,len = val.length;x<len;x++){
    	  	     var obj = $("dd[name="+dim+"]").find("a[scode="+val[x]+"]");
    	  	      //obj = obj.eq(0);
    	          styleChangeA({dim:dim,dom:this});
    	  	  }*/
    	  	   styleChangeA({dim:dim,dom:null});
    	       exeuteQuery({dim:dim,owner:$(this).text()});
    	  });
    	
     }
    function componentEventAbind(dim,dimArr){
    	 tools.console("给A--"+dim+"绑定了事件--->");
         $("dd[name="+dim+"] >a").unbind(); 
         $("dd[name="+dim+"] >a").click(function(){
	        var  dim = $(this).parent().attr("name"),scode = $(this).attr("scode"),
	        $obs = $('#'+dim+' option[value="'+scode+'"]');
	          var xx =  styleChangeA({dim:dim,dom:this});
	          if(xx.flag == "add"){
	             $obs.attr('selected',true); 
	          }else if(xx.flag == "remove"){
	              $obs.attr('selected',false); 
	          }else if(xx.flag == "single"){
	            $("#"+xx.dim).val(scode);
	          }
	         exeuteQuery({dim:dim,owner:$(this).text()});
	     });
    }
   /**
     * A组件事件
     * param obj Dom对象
     */
    function dimAEventBind(dimArr){
    	for(var i=0,len=dimArr.length;i<len-1;i++){
    	   componentEventAbind(dimArr[i],dimArr);
    	}
    }
     function createContextMenu(){
        var menu = {};
        menu['sure'] = {text:'确定',click:sureClickEvent};
        menu['allSelect']= {icon:'icon-arrow-left',text:'全选',click:allSelectEvent};
        menu['clearSelect']= {icon:'icon-arrow-right',text:'全不选',click:clearSelectEvent};
        $('#indicatorDiv').contextMenu(menu);
  
  }
    /**
     * 指标多选事件
     */
    function bindIndicatorDimOne(){
	    $(componentExp).bind('click',function(){
			  if(!$(this).hasClass(tools.cls)){
			     $(this).addClass(tools.cls)
			  }else{
			     $(this).removeClass(tools.cls).addClass("btn-default");
			  }
		 });
		 /* $(componentExp).bind('dbclick',function(){
			   alert("双击了"+$(this).text());
		 });*/
//		 $(componentExp).mousedown(function(e){
//			if(3 == e.which){
//			    sureClickEvent();
//			}else if(1 == e.which){
//			    if(!$(this).hasClass(tools.cls)){
//			     $(this).addClass(tools.cls)
//			    }else{
//			     $(this).removeClass(tools.cls).addClass("btn-default");
//			   }
//			}
//		})

     }
     /**
      * 指标多选事件
      * 年 月 公司 a事件
      * 年 月 公司 select事件
      */
     function dimComponentClick(dimArr){
     	bindIndicatorDimOne();
     	bindExpInDim(dimArr)
     	dimAEventBind(dimArr);
		dimSelectEventBind(dimArr)
     }
     function setManyDimInfo(){
     	var singleSelect = {flag:true};
     	for(var i=0,len=dimArr.length;i<len;i++){
     	    var obj = tools.getDimInfo(dimArr[i]);var temp = obj["dim"];
     	    if(singleSelect["dim"] == "month" || singleSelect["dim"] == "year"){
     	    	   temp = "period";
     	    	   singleSelect["dim"] = temp;
     	    }
     	    if(obj.size>1){
     	        tools.applyIf(singleSelect,obj);
     	    	singleSelect.flag = false;
     	    	 $("input[scode="+temp+"]").attr("checked",'true');//全选
     	    }else{
     	         $("input[scode="+temp+"]").removeAttr("checked");//
     	    }
     	}
        if(singleSelect["flag"] == false){
	    	var text = "<h4><strong>您选择的分析为多【<code>"+singleSelect.dimName+"</code>】",dims = singleSelect["dim"];
	    	 if(dims == "month" || dims == "year"){
		        text+="对比分析,也称【<code>趋势</code>】";
		     }else if( dims == "company"){
		        text+="对比";
		     }
		    $("#info").html(text+"分析</strong></h4>");
    	}else{
    	    $("#info").html("");
    	    $("input[scode="+singleSelect["dim"]+"]").attr("checked",'true');//全选
    	}
    	tools.console(">>>多选的是=="+singleSelect.dimName+singleSelect.dim);
    	manyDim = singleSelect;
     }
     /**
      * 获取期间维度组合
      */
     function getPeriod(params){
     	var dim={singleSelect:true};
     	for(var key in params){
              var len = params[key].length;
              if(len > 1){
                  dim["name"] = key;
                  params["showDim"] = [dim["name"]];
                  dim["singleSelect"] = false;
                  if(params["showDim"][0] == "month" || params["showDim"][0] == "year"){
                      params["showDim"][0] = "period";
                  }
              }
         }
         var period = [];
         var yearLen = params["year"].length,monthLen =  params["month"].length;
	              for(var i=0;i<yearLen;i++){
	                  for(var j=0;j<monthLen;j++){
	                  	if(params["year"][i].length>4){
	                  	     params["year"][i] = params["year"][i].substring(0,4);
	                  	}
	                   period.push(params["year"][i]+params["month"][j]);
	                 }
	              }
     	return period;
     }
     var chartDatas = null;
     function getChartDatas(swf){
     	  defaultChartSwf = swf;
     	      if(chartDatas !=null){
     	      	 tools.console(swf+"利用了缓存的 chartDatas;");
     	      	 chartDatas["swf"] = swf ;
     	      	 chartDatas["chartId"] = swf+"chartId";
     	         return chartDatas;
     	      }
          	  var $obj = $("#indicatrTbody").children();
              var len = $obj.size();
              if(len == 0){
                tools.alertMsg("请查询数据后再做此操作！");
                return ;
              }
              var value = [],label=[],dimCode = manyDim["dim"] ;
              if(dimCode == "month" || dimCode == "year") dimCode = "period";
              $obj.each(function(index,o){
                  var $temp = $(o).children(); //alert($temp.length);
                   $temp.each(function(index,bean){
                   	   var scode = $(bean).attr("hiddenflag");
                          if(dimCode == scode){
		                     label.push($(bean).attr("title"));
		                  }if(scode == "datas"){
		                     value.push($(bean).text());
		                  }
                   
                   })
                 
              });
               var caption = "多【"+manyDim["dimName"]+"】--",
                      company = tools.getDimInfo("company"),
                      companyName = company["value"][0]["name"],
                      indicator = tools.getDimInfo("indicator"),
                      indicatorName=indicator["value"][0]["name"],
                      periodName = queryParams["period"]+"期间";
               if(manyDim["dim"] == "indicator"){
                     caption+=companyName+"--"+periodName;
               }else if(manyDim["dim"] == "period"){
                      caption+=companyName+"--"+indicatorName;
               }else if(manyDim["dim"] == "company"){
                    caption+=indicatorName+"--"+periodName;
               }else{
                 caption = companyName+indicatorName+periodName
               }
               caption+="动态展示图";
               chartDatas = {chart:{caption:caption},label:label,value:value,domId:'chartId',swf:swf,height:300};
              return  chartDatas;
              
     }
     function chartGroup(){
          $("#chartGroup>li >a").bind("click",function(){
               chart.createSingleSeriesChart(getChartDatas($(this).attr("id")));
          });
     }
    /**
     * 执行查询事件
     */
     function exeuteQuery(bean){
     	  tools.mask();
     	 var params = tools.getDimParams(dimArr);
         params["period"] = getPeriod(params);
         delete params.month;
         delete params.year;
         queryParams = params;
         for(var key in params){
            params[key] = params[key].join(",");
         }
         if(!params["showDim"])params["showDim"] = "indicator";
         tools.applyIf(params,Utils.bean);//把所有obj变量的所有属性都 给bean变量
         params.level = (params.level-0)+1;
         tools.console(params);
         setManyDimInfo();
         function success(msg){//+tableId
			//$("#tableId").remove();
			//$("#modelId").remove();
			//$("#chartId").remove();
			$("#dataContent").empty().append(msg);
			chartDatas = null;
			chart.createSingleSeriesChart(getChartDatas(defaultChartSwf));
			//setTimeout(function(){
			////  setColDimShowOrHide(showColDim);
			//},100);
			//// tools.alertMsg(tableIds);
			//// tools.alertMsg(msg);
			 tools.unmask();
		}
		var url = tools.getBasePathUrl() + params.spcode+tools.dataUrl;
		//tools.alertMsg(url);
        tools.ajax({url : url,dataType : 'html',data :params,success:success});
     }
    
     function setColDimShowOrHide(showColDim){//if($("#id").attr("checked")==true)
        for(var j=0,len = showColDim.length;j<len;j++){
        	var scode  = $("#"+showColDim[j]).attr("scode") ;
           if($("#"+showColDim[j]).attr("checked")){
               $(".apply[hiddenFlag = "+scode+"]").show();//.fadeIn();
           }else{
               $(".apply[hiddenFlag = "+scode+"]").hide();//.fadeOut();
           }
	      }
     }
    function columnShow(){
	   	for(var i=0,len = showColDim.length;i<len;i++){
	   	  $("#"+showColDim[i]).bind("change",function(){
	   	  	  setColDimShowOrHide(showColDim);
	     });
	   	}
    /* $("#inputIndicator,#inputCompany,#inputPeriod").bind("change",function(){
          alert($(this).attr("id")+"value===="+$(this).val());
     });*/
   }  
  /**
   * 第二级别导航点击成功后的处理
   */
  function success(msg){
		tools.levelNav(Utils.bean);
		$("#"+domId).empty().append(msg);
		//指标分析 和 科目分析
		if(Utils.bean.scode != 'kemu'){
			tools.viewChange();
			tools.bindPanelHeaderDbClick();
		    dimArr = tools.getDimArrByMap(Utils.dimMapJson);//dblclick
			dimComponentClick(dimArr);
			//$(componentExp).tooltip({animation:false,placement:'bottom'});
			allSelect();
			clearSelect();
			sureClick();
			letterEventBind();
			btnGroupBind();
		}else{
			kemu.init();
		}
		createContextMenu();
		columnShow();
		chartGroup();
		tools.unmask();
		//<th hiddenFlag="inputIndicator">指标名称</th>
        //<th hiddenFlag="inputCompany">公司名称</th>
        //<th hiddenFlag="inputPeriod">查询期间</th>
   }
   function addProgress(){
     var pro= '<div class="progress progress-striped active"><div class="progress-bar"  role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 45%"><span class="sr-only">45% Complete</span></div></div>';
     $("#content").append(pro);
     }
  /** 
   * 初始方法
   */
  function init (){
  	  //$("#content").mask("正在为您加载数据，请稍做等候………………");
  	  //addProgress();
  	  tools.eventBind({domId:domId,tableId:tableId,success:success});
  	  
   }
  return {
    init: init
  }
});